//
//  SLRefreshControl.swift
//  Sina15
//
//  Created by 盼 on 16/4/16.
//  Copyright © 2016年 pan. All rights reserved.
//

import UIKit
import SnapKit

enum SLRefreshState: Int {
    case Normal = 0 //普通状态
    case Pulling = 1 //准备刷新
    case Refreshing = 2 //正在刷新
}

private let refreshControlHeight:CGFloat = 60
class SLRefreshControl: UIControl {

    //父控件
    var scrollView: UIScrollView?
    
    //刷新控件的状态
    var currentState: SLRefreshState = .Normal {
        didSet {
            switch currentState{
            case .Normal:
                textLabel.text = "下拉刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrow.transform = CGAffineTransformIdentity
                })
                indicatorView.stopAnimating()
                arrow.hidden = false
                
                if oldValue == .Refreshing {
                    var inset = scrollView!.contentInset
                    inset.top = inset.top - refreshControlHeight
                    scrollView!.contentInset = inset
                }
            case .Pulling:
                textLabel.text = "准备刷新"
                //箭头旋转180度
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrow.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                textLabel.text = "正在刷新"
                arrow.hidden = true
                //向控件发送消息通知
                 sendActionsForControlEvents(.ValueChanged)
                indicatorView.startAnimating()
                
                //刷新的时候，让刷新控件悬停
                var inset = scrollView!.contentInset
                inset.top = inset.top + refreshControlHeight
                scrollView!.contentInset = inset
            }
        }
    }
    
    func endRefreshing(){
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.5))
        
        dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
            self.currentState = .Normal
        }
}
    
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshControlHeight, width: screenWidth, height: refreshControlHeight)
        super.init(frame: rect)
        
        backgroundColor = UIColor.yellowColor()
        //设置UI界面
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //被观察对象的指定键值属性变化时调用的方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //实时获取父视图的垂直方向位移  和 -124 比较 修改视图的状态
        // 需要有一个监测用户是否 '正在拖拽' 滚动视图
        let offsetY = scrollView!.contentOffset.y
        
        print(scrollView!.contentInset)
        print(offsetY)
        
        if scrollView!.dragging {
            let targetOffset = scrollView!.contentInset.top + refreshControlHeight
            if currentState == .Pulling && offsetY > -targetOffset {
                currentState = .Normal
                print("下拉刷新")
            }else if currentState == .Normal && offsetY < -targetOffset {
                print("准备刷新")
                currentState = .Pulling
            }
        }else if currentState == .Pulling {
           print("正在刷新")
            currentState = .Refreshing
        }
        
    }
    
    //要根据父视图的contentOffset来判断是否进行刷新
    //首先要获取父控件
    override func willMoveToSuperview(newSuperview: UIView?) {
        //一定要调用父类的方法
        super.willMoveToSuperview(newSuperview)
        
        if let myFather = newSuperview as? UIScrollView{
            self.scrollView = myFather
            
            //观察某个对象的某个键值属性的变化
            myFather.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        }
    }

    
    //移除观察对象
    deinit{
        
       scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    //设置UI
    func setupUI() {
        
        //添加子控件
        addSubview(arrow)
        addSubview(textLabel)
        addSubview(indicatorView)
        
        //设置约束
        arrow.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        textLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(arrow.snp_right)
            make.centerY.equalTo(self.snp_centerY)
        }
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrow.snp_center)
        }
        
    }
    
    //箭头
    private lazy var arrow: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //提示文字
    private lazy var textLabel: UILabel = UILabel(labelText: "下拉刷新", color: UIColor.darkGrayColor(), fontsize: 14)
    
    //刷新指示器
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
}
